<script setup>
import { ref, onMounted, computed } from 'vue'
import { Delete, Edit, Search } from '@element-plus/icons-vue'
import ArticleEdit from './component/ArticleEdit.vue'
import ContractShow from './component/ContractShow.vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { exportToExcel, exportContractsByQuery } from '@/utils/export' 
import { useContractStore } from '@/stores/contractStore'
import axios from 'axios'
const contractStore = useContractStore()

const filteredList = ref([]) // 用于存储筛选后的结果
// 创建axios实例
const api = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL,
  timeout: 5000
})
// 添加合同类型选项
const contractTypes = ref([
  { label: '全部', value: '全部' },
  { label: '租赁合同', value: '租赁合同' },
  { label: '服务合同', value: '服务合同' },
  { label: '合作协议', value: '合作协议' }
])

// 合同状态选项
const contractStatusOptions = ref([
  { label: '全部', value: '全部' },
  { label: '待审批', value: '待审批' },
  { label: '已签署', value: '已签署' },
  { label: '即将到期', value: '即将到期' },
  { label: '已逾期', value: '已逾期' },
  { label: '已终止', value: '已终止' },
  { label: '生效中', value: '生效中' }
])

const total = ref(0) // 总条数
const loading = ref(false) // loading状态

const articleEditRef = ref()
const contractShowRef = ref()

// 计算当前页显示的数据
const paginatedList = computed(() => {
  const start = (params.value.pagenum - 1) * params.value.pagesize
  const end = start + params.value.pagesize
  return filteredList.value.slice(start, end)
})

// 表格数据使用分页后的数据
const tableData = computed(() => {
  return paginatedList.value
})

// 添加逻辑
const onAddArticle = () => {
  articleEditRef.value.open({})
}

// 编辑逻辑
const onEditArticle = (row) => {
  articleEditRef.value.open(row)
}

// 显示合同详情页逻辑
const onViewContract = (row) => {
  console.log('当前合同数据:', row)
  contractShowRef.value.open(row)
}

// 删除逻辑
const onDeleteArticle = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除合同 "${row.title}" (编号: ${row.contractNumber}) 吗？`,
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 调用删除API
    const response = await fetch(`${import.meta.env.VITE_API_BASE_URL}/api/contracts/${row.id}`, {
      method: 'DELETE'
    })
    
    if (response.ok) {
      ElMessage.success('合同删除成功')
      // 重新加载数据
      await searchContracts()
    } else {
      const errorData = await response.json()
      ElMessage.error('删除失败: ' + (errorData.message || '未知错误'))
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败: ' + error.message)
    }
  }
}

// 定义请求参数对象
const params = ref({
  pagenum: 1,
  pagesize: 5,
  status: undefined,
  type: undefined,
  startDate: undefined,
  contractNumber: undefined,
  title: undefined,
  companyName: undefined
})

// 处理分页逻辑
const onSizeChange = (size) => {
  console.log('当前页面条数', size)
  params.value.pagenum = 1
  params.value.pagesize = size
}

const onCurrentChange = (page) => {
  console.log('页码变化了', page)
  params.value.pagenum = page
}

// 条件搜索合同
const searchContracts = async () => {
  loading.value = true
  try {
    // 构建搜索参数
    const searchParams = {
      contractStatus: params.value.status === '全部' ? undefined : params.value.status,
      contractType: params.value.type === '全部' ? undefined : params.value.type,
      startDate: params.value.startDate
    }
    
    // 过滤掉undefined的参数
    const filteredParams = Object.fromEntries(
      Object.entries(searchParams).filter(([_, value]) => value !== undefined && value !== '')
    )
    
    console.log('搜索参数:', filteredParams)
    
    const response = await fetch(`${import.meta.env.VITE_API_BASE_URL}/api/contracts/search`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(filteredParams)
    })
    
    if (response.ok) {
      const data = await response.json()
      if (data.success) {
        filteredList.value = data.data
        total.value = data.data.length
        ElMessage.success(`找到 ${data.data.length} 条合同`)
      } else {
        ElMessage.error('搜索失败: ' + data.message)
      }
    } else {
      ElMessage.error('搜索请求失败')
    }
  } catch (error) {
    ElMessage.error('搜索合同失败: ' + error.message)
  } finally {
    loading.value = false
  }
}

// 搜索逻辑
const onSearch = () => {
  params.value.pagenum = 1
  searchContracts()
}

// 重置逻辑
const onReset = () => {
  params.value.pagenum = 1
  params.value.status = undefined
  params.value.type = undefined
  params.value.startDate = undefined
  params.value.contractNumber = undefined
  params.value.title = undefined
  params.value.companyName = undefined
  // 重置后加载所有数据
  loadAllContracts()
}

// 加载所有合同数据
const loadAllContracts = async () => {
  loading.value = true
  try {
    const response = await fetch(`${import.meta.env.VITE_API_BASE_URL}/api/contracts`)
    if (response.ok) {
      const data = await response.json()
      if (data.success) {
        filteredList.value = data.data
        total.value = data.data.length
      } else {
        ElMessage.error('获取合同列表失败: ' + data.message)
      }
    } else {
      ElMessage.error('网络请求失败')
    }
  } catch (error) {
    ElMessage.error('加载合同数据失败: ' + error.message)
  } finally {
    loading.value = false
  }
}

// 在组件挂载时初始化数据
onMounted(() => {
  loadAllContracts()
})

// 接收子组件事件
const onArticleAdded = (updatedContract) => {
  // 重新加载数据
  searchContracts()
  ElMessage.success(updatedContract.id ? '合同更新成功' : '合同新增成功')
}

// 处理选择变化
const selectedContracts = ref([])
const handleSelectionChange = (selection) => {
  selectedContracts.value = selection
}



// 批量导出选中项
const onExportSelected = async () => {
  if (selectedContracts.value.length === 0) {
    ElMessage.warning('请先选择要导出的合同');
    return;
  }
  
  try {
    const exportData = selectedContracts.value.map(item => ({
      '合同编号': item.contractNumber,
      '合同名称': item.title,
      '申请人': item.applicant,
      '企业名称': item.companyName,
      '企业地址': item.companyAddress,
      '合同类型': item.contractType,
      '生效日期': item.startDate,
      '到期日期': item.endDate,
      '合同状态': item.contractStatus,
      '创建时间': item.createdAt,
      '更新时间': item.updatedAt
    }));
    
 // 如果有多个选中项，使用第一个合同的名称作为文件名
    const fileName = selectedContracts.value.length === 1 
      ? selectedContracts.value[0].title 
      : `批量合同_${new Date().toISOString().slice(0,10)}`;
    
    exportToExcel(exportData, fileName);
    ElMessage.success(`成功导出 ${selectedContracts.value.length} 条合同`);
  } catch (error) {
    ElMessage.error('导出失败: ' + error.message);
  }
}
</script>

<template>
  <div class="contract-approval">
    <!-- 标题和分割线 -->
    <div class="header-section">
      <h1 class="contract-title">合同列表</h1>
      <div class="divider"></div>
    </div>
    
    <!-- 表单区域 -->
    <el-form inline style="display: flex; justify-content: space-between; align-items: center; width: 100%;">
      <div style="display: flex; flex-wrap: wrap; gap: 10px;">
        <el-form-item label="合同状态">
          <el-select v-model="params.status" style="width:120px" placeholder="合同状态">
            <el-option 
              v-for="status in contractStatusOptions" 
              :key="status.value" 
              :label="status.label" 
              :value="status.value"
            ></el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="合同类型">
          <el-select v-model="params.type" style="width:120px" placeholder="合同类型">
            <el-option 
              v-for="type in contractTypes" 
              :key="type.value" 
              :label="type.label" 
              :value="type.value"
            ></el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="生效日期">
          <el-date-picker
            v-model="params.startDate"
            type="date"
            placeholder="选择日期"
            value-format="YYYY-MM-DD"
            style="width:150px"
          />
        </el-form-item>
        
        <el-form-item>
          <el-button @click="onSearch" type="primary">查询</el-button>
          <el-button @click="onReset">重置</el-button>
        </el-form-item>
      </div>
      
      <el-form-item>
        <el-button 
          type="primary" 
          @click="onExportSelected"
          style="width: 80px"
          :disabled="selectedContracts.length === 0"
        >
          批量导出
        </el-button>
        <el-button @click="onAddArticle">录入合同</el-button>
      </el-form-item>
    </el-form>
    
    <!-- 表格区域 -->
    <el-table 
      :data="tableData" 
      v-loading="loading"
      border
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column type="index" label="序号" width="80px" fixed></el-table-column>
      <el-table-column label="合同编号" prop="contractNumber" width="150px"></el-table-column>
      <el-table-column label="合同名称" prop="title" width="180px"></el-table-column>
      <el-table-column label="企业名称" prop="companyName" width="180px"></el-table-column>
      <el-table-column label="申请人" prop="applicant" width="100px"></el-table-column>       
      <el-table-column label="合同类型" prop="contractType" width="100px"></el-table-column>
      <el-table-column label="生效日期" prop="startDate" width="150px"></el-table-column>
      <el-table-column label="合同状态" prop="contractStatus" width="100px">
        <template #default="{ row }">
          <el-tag :type="row.contractStatus === '已签署' ? 'success' : 
                         row.contractStatus === '待审批' ? 'warning' : 
                         row.contractStatus === '已逾期' ? 'danger' : 'info'">
            {{ row.contractStatus }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200px" fixed="right">
        <template #default="{ row }">
          <el-button circle plain type="primary" :icon="Search" @click="onViewContract(row)"></el-button>
          <el-button circle plain type="primary" :icon="Edit" @click="onEditArticle(row)"></el-button>
          <el-button circle plain type="danger" :icon="Delete" @click="onDeleteArticle(row)"></el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页区域 -->
    <el-pagination
      v-model:current-page="params.pagenum"
      v-model:page-size="params.pagesize"
      :page-sizes="[5, 10, 20, 50]"
      :background="true"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="onSizeChange"
      @current-change="onCurrentChange"
      style="margin-top: 20px; justify-content: flex-end;"
    />

    <article-edit 
      ref="articleEditRef" 
      @article-added="onArticleAdded"
    ></article-edit>
     
    <!-- 合同详情页 -->
    <contract-show ref="contractShowRef"></contract-show>
  </div>
</template>

<style lang="scss" scoped>
.el-dropdown {
  margin-left: 10px
}
.divider {
  height: 1px;
  background-color: #e0e0e0;
  width: 100%;
}
.contract-title {
  font-size: 20px;
  color: #333;
  margin-bottom: 10px;
  text-align: left;
}
.header-section {
  margin-bottom: 30px;
}
.contract-approval {
  padding: 20px;
  font-family: 'Arial', sans-serif;
  border-radius: 8px;
  background-color: #fff;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}
</style>